package asteroids.model.programs.statements;

import java.util.ArrayList;

import exception.StopActionClassException;


import asteroids.model.SpaceObject;
import asteroids.model.programs.Program;
import asteroids.model.programs.parsing.ProgramFactory.ForeachType;

public class Foreach extends Statement{

	public Foreach(ForeachType type, String variable,Statement statement){
		this.type=type;
		this.variable=variable;
		this.statement=statement;
	}
	
	private ForeachType type;
	private String variable;
	private Statement statement;
	
	@SuppressWarnings("unchecked")
	@Override
	public void execute(Program program) throws StopActionClassException {
		if(!isExecuted()){
		ArrayList<SpaceObject> objects = new ArrayList<SpaceObject>();
		try{
		objects = getObjects(program);
		for(SpaceObject object: objects){
		program.getGlobals().get(variable).setValue(object);
		statement.execute(program);
		statement.reset();
		}
		}
		catch(NullPointerException e){
		}}
		setExecuted();
		statement.setExecuted();
	}
	
	public ArrayList<SpaceObject> getObjects(Program program){
		if(this.type == ForeachType.ASTEROID)
			return new ArrayList<SpaceObject>(program.getShip().getWorld().getAllAsteroids());
		else if(this.type == ForeachType.SHIP)
			return new ArrayList<SpaceObject>(program.getShip().getWorld().getAllShips());
		else if(this.type == ForeachType.BULLET)
			return new ArrayList<SpaceObject>(program.getShip().getWorld().getAllBullets());
		else if(this.type == ForeachType.ANY)
			return new ArrayList<SpaceObject>(program.getShip().getWorld().getAllSpaceObjects());
		return null;
	}

	@Override
	public void reset() {
		setUnexecuted();
		statement.reset();
	}

}
